package com.itheima.service.Impl;

import com.itheima.mapper.UsersMapper;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    // UserDetailServiceImpl.java
    @Override
    public UserDetails loadUserByUsername(String telephone) throws UsernameNotFoundException {
        // 改为通过手机号查询用户
        User user = usersMapper.findByTelephone(telephone);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }
    // 新方法：根据手机号加载用户
    public User loadUserByTelephone(String telephone) {
        return usersMapper.findByTelephone(telephone);
    }

    // 新方法：注册用户
    public void register(User user) {
        // 加密随机密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        usersMapper.insertUser(user);
    }
}
